﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using CarolLib.Control;
using DispatchAssist.Service;
using System.Web.Services.Protocols;
using System.Text.RegularExpressions;

namespace DispatchAssist.AppHost
{
    [ModuleContract("251bd5b0-7584-4c2e-8824-42654bf188f1", "系统管理", "通讯录管理")]
    public partial class ContactManage : MdiUserControl
    {
        AuthService authService = new AuthService();
        List<SMSContactGroup> lstGroups = new List<SMSContactGroup>();
        List<SMSContact> lstContacts = new List<SMSContact>();
        public ContactManage()
            : base()
        {
            InitializeComponent();

        }
        public ContactManage(XmlNode node)
            : this()
        {
        }

        private void cMenuItemAddGroup_Click(object sender, EventArgs e)
        {
            if (this.tvContacts.SelectedNode != null && this.tvContacts.SelectedNode.Tag.GetType().Name == "String" && this.tvContacts.SelectedNode.Tag.ToString() == "root")
            {
                this.btnSaveGroup.Tag = "create";
                this.btnSaveGroup.Visible = true;
                this.txtGroupCode.Text = string.Empty;
                this.txtGroupName.Text = string.Empty;
                this.txtGroupCode.ReadOnly = false;
                this.txtGroupName.ReadOnly = false;
                this.btnSaveGroup.Visible = true;
                this.pnlGroup.Visible = true;
                this.pnlContact.Visible = false;
            }
            else
            {
                MessageBox.Show("请选择根目录，只可以在根目录下添加公司！");
            }
        }

        private void cMenuItemEditGroup_Click(object sender, EventArgs e)
        {
            if (this.tvContacts.SelectedNode != null && this.tvContacts.SelectedNode.Tag.GetType().Name == "SMSContactGroup")
            {
                SMSContactGroup group = (SMSContactGroup)this.tvContacts.SelectedNode.Tag;
                this.btnSaveGroup.Tag = group.SMSContactGroupID;
                this.txtGroupCode.Text = group.GroupCode;
                this.txtGroupName.Text = group.GroupName;
                this.txtGroupCode.ReadOnly = false;
                this.txtGroupName.ReadOnly = false;
                this.btnSaveGroup.Visible = true;
                this.pnlGroup.Visible = true;
                this.pnlContact.Visible = false;
            }
            else
            {
                MessageBox.Show("请选择要编辑的公司！");
            }
        }

        private void cMenuItemDeleteGroup_Click(object sender, EventArgs e)
        {
            if (this.tvContacts.SelectedNode == null || this.tvContacts.SelectedNode.Tag.GetType().Name != "SMSContactGroup")
            {
                MessageBox.Show("请选择要删除的公司！");
                return;
            }
            if (MessageBox.Show("确认删除此公司？", "删除确认", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                return;
            }
            SMSContactGroup group = (SMSContactGroup)this.tvContacts.SelectedNode.Tag;
            try
            {
                if (authService.DeleteSMSContactGroup(group.SMSContactGroupID))
                {
                    this.tvContacts.SelectedNode.Remove();
                    this.tvContacts.Refresh();
                    MessageBox.Show("删除成功！");
                }
                else
                {
                    MessageBox.Show("删除失败！");
                }
                this.pnlContact.Visible = false;
                this.pnlGroup.Visible = false;

            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        private void cMenuItemAddContact_Click(object sender, EventArgs e)
        {
            if (this.tvContacts.SelectedNode == null || this.tvContacts.SelectedNode.Tag.GetType().Name != "SMSContactGroup")
            {
                MessageBox.Show("请选择要添加联系人所在的公司！");
                return;
            }
            BindGroup();
            SMSContactGroup group = (SMSContactGroup)this.tvContacts.SelectedNode.Tag;
            this.cmbGroup.SelectedValue = group.SMSContactGroupID;
            this.txtName.Text = string.Empty;
            this.txtMoble.Text = string.Empty;
            this.txtName.ReadOnly = false;
            this.txtMoble.ReadOnly = false;
            this.cmbGroup.Enabled = true;
            this.btnSaveContact.Visible = true;
            this.btnSaveContact.Tag = "create";
            this.pnlContact.Visible = true;
            this.pnlGroup.Visible = false;
        }

        private void BindGroup()
        {
            if (lstGroups[0].GroupName != "请选择公司")
            {
                lstGroups.Insert(0, new SMSContactGroup() { SMSContactGroupID = new Guid(), GroupName = "请选择公司" });
            }
            cmbGroup.DataSource = lstGroups;
            cmbGroup.DisplayMember = "GroupName";
            cmbGroup.ValueMember = "SMSContactGroupID";
        }

        private void cMenuItemEditContact_Click(object sender, EventArgs e)
        {
            if (this.tvContacts.SelectedNode == null || this.tvContacts.SelectedNode.Tag.GetType().Name != "SMSContact")
            {
                MessageBox.Show("请选择要编辑的联系人！");
                return;
            }
            SMSContact contact = (SMSContact)this.tvContacts.SelectedNode.Tag;
            BindGroup();
            SMSContactGroup group = (SMSContactGroup)this.tvContacts.SelectedNode.Parent.Tag;
            this.cmbGroup.SelectedValue = group.SMSContactGroupID;
            this.txtName.Text = contact.ContactName;
            this.txtMoble.Text = contact.ContactMobile;
            this.txtName.ReadOnly = false;
            this.txtMoble.ReadOnly = false;
            this.cmbGroup.Enabled = true;
            this.btnSaveContact.Visible = true;
            this.btnSaveContact.Tag = contact.SMSContactID;
            this.pnlContact.Visible = true;
            this.pnlGroup.Visible = false;
        }

        private void cMenuItemDeleteContact_Click(object sender, EventArgs e)
        {
            if (this.tvContacts.SelectedNode == null || this.tvContacts.SelectedNode.Tag.GetType().Name != "SMSContact")
            {
                MessageBox.Show("请选择要删除的联系人！");
                return;
            }
            if (MessageBox.Show("确认删除此联系人？", "删除确认", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                return;
            }
            this.pnlContact.Visible = false;
            this.pnlGroup.Visible = false;
            SMSContact contact = (SMSContact)this.tvContacts.SelectedNode.Tag;
            try
            {
                if (authService.DeleteSMSContact(contact.SMSContactID))
                {
                    this.tvContacts.SelectedNode.Remove();
                    this.tvContacts.Refresh();
                    MessageBox.Show("删除成功！");
                }
                else
                {
                    MessageBox.Show("删除失败！");
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        private void btnSaveGroup_Click(object sender, EventArgs e)
        {
            string tag = System.Convert.ToString((sender as Button).Tag);
            if (string.IsNullOrEmpty(this.txtGroupName.Text))
            {
                MessageBox.Show("请输入公司名称！");
                return;
            }
            if (string.IsNullOrEmpty(this.txtGroupCode.Text))
            {
                MessageBox.Show("请输入公司代码！");
                return;
            }
            if (tag == "create")
            {
                if (this.tvContacts.SelectedNode != null && this.tvContacts.SelectedNode.Tag.GetType().Name == "String" && this.tvContacts.SelectedNode.Tag.ToString() == "root")
                {
                    SaveNewGroup();
                }
                else
                {
                    MessageBox.Show("请选择根目录，只可以在根目录下添加公司！");
                }
            }
            else if (!string.IsNullOrEmpty(tag))
            {
                if (this.tvContacts.SelectedNode != null && this.tvContacts.SelectedNode.Tag.GetType().Name == "SMSContactGroup")
                {
                    SaveEditGroup(tag);
                }
                else
                {
                    MessageBox.Show("请选择要编辑的公司！");
                }
            }
        }
        private void SaveEditGroup(string groupID)
        {
            SMSContactGroup group = new SMSContactGroup();
            group.SMSContactGroupID = new Guid(groupID);
            group.GroupName = this.txtGroupName.Text;
            group.GroupCode = this.txtGroupCode.Text;
            try
            {
                DataAccessReturnValue result = authService.UpdateSMSContactGroup(group);
                if (result == DataAccessReturnValue.无法更新)
                {
                    MessageBox.Show("该公司代码已存在！");
                }
                else if (result == DataAccessReturnValue.更新成功)
                {
                    lstGroups = authService.GetContactGroup().ToList<SMSContactGroup>();

                    TreeNode nodeGroup = new TreeNode(group.GroupName + "(" + group.GroupCode + ")");
                    nodeGroup.Name = System.Convert.ToString(group.SMSContactGroupID);
                    nodeGroup.Tag = group;
                    nodeGroup.ContextMenuStrip = this.ctxMenuGroup;

                    TreeNodeCollection collection = this.tvContacts.SelectedNode.Nodes;
                    if (collection != null && collection.Count > 0)
                    {
                        foreach (TreeNode tn in collection)
                        {
                            this.tvContacts.SelectedNode.Nodes.Remove(tn);
                            nodeGroup.Nodes.Add(tn);
                        }
                    }
                    this.tvContacts.SelectedNode.Remove();
                    this.tvContacts.SelectedNode.Parent.Nodes.Add(nodeGroup);

                    this.tvContacts.SelectedNode = nodeGroup;
                    this.tvContacts.Refresh();
                    MessageBox.Show("保存成功！");
                }
                else
                {
                    MessageBox.Show("保存失败！");
                }

            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        private void SaveNewGroup()
        {
            SMSContactGroup group = new SMSContactGroup();
            group.GroupName = this.txtGroupName.Text;
            group.GroupCode = this.txtGroupCode.Text;
            try
            {
                DataAccessReturnValue result = authService.CreateSMSContactGroup(group);
                if (result == DataAccessReturnValue.无法更新)
                {
                    MessageBox.Show("该公司代码已存在！");
                }
                else if (result == DataAccessReturnValue.更新成功)
                {
                    lstGroups = authService.GetContactGroup().ToList<SMSContactGroup>();

                    SMSContactGroup smsgroup = lstGroups.Find(s => s.GroupCode == group.GroupCode);
                    group = smsgroup;
                    TreeNode nodeGroup = new TreeNode(group.GroupName + "(" + group.GroupCode + ")");
                    nodeGroup.Name = System.Convert.ToString(group.SMSContactGroupID);
                    nodeGroup.Tag = group;
                    nodeGroup.ContextMenuStrip = this.ctxMenuGroup;
                    this.tvContacts.SelectedNode.Nodes.Add(nodeGroup);
                    this.tvContacts.SelectedNode = nodeGroup;
                    this.tvContacts.Refresh();
                    MessageBox.Show("添加成功！");
                }
                else
                {
                    MessageBox.Show("添加失败！");
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        private void btnSaveContact_Click(object sender, EventArgs e)
        {
            string tag = System.Convert.ToString((sender as Button).Tag);
            if (string.IsNullOrEmpty(this.txtName.Text))
            {
                MessageBox.Show("请输入姓名！");
                return;
            }
            if (string.IsNullOrEmpty(this.txtMoble.Text))
            {
                MessageBox.Show("请输入手机！");
                return;
            }

            if (!IsValidateOfMobile(this.txtMoble.Text))
            {
                MessageBox.Show("无效的手机号码！");
                this.txtMoble.Focus();
                return;
            }


            if (((SMSContactGroup)(this.cmbGroup.SelectedItem)).GroupName == "请选择公司")
            {
                MessageBox.Show("请选择公司！");
                return;
            }
            if (tag == "create")
            {
                if (this.tvContacts.SelectedNode != null && this.tvContacts.SelectedNode.Tag.GetType().Name == "SMSContactGroup")
                {
                    SaveNewContact();
                }
                else
                {
                    MessageBox.Show("请选择要添加联系人所在的公司！");
                }
            }
            else if (!string.IsNullOrEmpty(tag))
            {
                if (this.tvContacts.SelectedNode != null && this.tvContacts.SelectedNode.Tag.GetType().Name == "SMSContact")
                {
                    SaveEditContact(tag);
                }
                else
                {
                    MessageBox.Show("请选择要编辑的联系人！");
                }
            }
        }

        private void SaveEditContact(string contactID)
        {
            SMSContact contact = new SMSContact();
            contact.SMSContactID = new Guid(contactID);
            contact.ContactName = this.txtName.Text;
            contact.ContactMobile = this.txtMoble.Text;
            contact.SMSContactGroupID = ((SMSContactGroup)(this.cmbGroup.SelectedItem)).SMSContactGroupID;
            try
            {
                if (authService.UpdateSMSContact(contact))
                {
                    BindContactBook();
                    MessageBox.Show("保存成功！");
                }
                else
                {
                    MessageBox.Show("保存失败！");
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        private void SaveNewContact()
        {
            SMSContact contact = new SMSContact();
            contact.ContactName = this.txtName.Text;
            contact.ContactMobile = this.txtMoble.Text;
            contact.SMSContactGroupID = ((SMSContactGroup)(this.cmbGroup.SelectedItem)).SMSContactGroupID;
            try
            {
                if (authService.CreateSMSContact(contact))
                {
                    BindContactBook();
                    MessageBox.Show("保存成功！");
                    this.btnSaveContact.Visible = false;
                    this.txtName.ReadOnly = true;
                    this.txtMoble.ReadOnly = true;
                    this.cmbGroup.Enabled = false;
                }
                else
                {
                    MessageBox.Show("保存失败！");
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }
        public override void Onload()
        {
            base.Onload();
            authService.DASoapHeaderValue = AuthContext.Current.GetSoapHeader();
            BindContactBook();
            this.pnlContact.Visible = false;
            this.pnlGroup.Visible = false;
        }


        private void BindContactBook()
        {
            TreeNode nodeRoot = new TreeNode("通讯录");
            nodeRoot.Name = "-1";
            nodeRoot.Tag = "root";
            BuildGroups(nodeRoot);
            nodeRoot.ContextMenuStrip = this.ctxMenuRoot;
            nodeRoot.Expand();
            this.tvContacts.Nodes.Clear();
            this.tvContacts.Nodes.Add(nodeRoot);

        }

        private void BuildGroups(TreeNode nodeRoot)
        {
            try
            {
                //todo: 请重构方法，使用一次webservice调用完成
                lstGroups = authService.GetContactGroup().ToList<SMSContactGroup>();
                lstContacts = authService.GetAllSMSContacts().ToList<SMSContact>();
                foreach (SMSContactGroup group in lstGroups)
                {
                    TreeNode nodeGroup = new TreeNode(group.GroupName + "(" + group.GroupCode + ")");
                    nodeGroup.Name = System.Convert.ToString(group.SMSContactGroupID);
                    nodeGroup.Tag = group;
                    nodeGroup.ContextMenuStrip = this.ctxMenuGroup;
                    BuildContact(nodeGroup, lstContacts);
                    nodeRoot.Nodes.Add(nodeGroup);
                }

            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        private void BuildContact(TreeNode nodeGroup, List<SMSContact> lstContacts)
        {
            List<SMSContact> groupContact = lstContacts.Where<SMSContact>(m => m.SMSContactGroupID == new Guid(nodeGroup.Name)).ToList<SMSContact>();
            foreach (SMSContact contact in groupContact)
            {
                TreeNode nodeContact = new TreeNode(contact.ContactName);
                nodeContact.Name = System.Convert.ToString(contact.SMSContactID);
                nodeContact.Tag = contact;
                nodeContact.ContextMenuStrip = this.ctxMenuContact;
                nodeGroup.Nodes.Add(nodeContact);
            }
        }

        private void tvContacts_AfterSelect(object sender, TreeViewEventArgs e)
        {
            string tag = System.Convert.ToString(this.tvContacts.SelectedNode.Tag);
            if (this.tvContacts.SelectedNode.Level == 0)
            {
                pnlContact.Visible = false;
                pnlGroup.Visible = false;
            }
            else if (this.tvContacts.SelectedNode.Level == 1)
            {
                pnlContact.Visible = false;
                pnlGroup.Visible = true;
                this.btnSaveGroup.Visible = false;
                this.txtGroupCode.ReadOnly = true;
                this.txtGroupName.ReadOnly = true;
                SMSContactGroup group = (SMSContactGroup)this.tvContacts.SelectedNode.Tag;
                this.txtGroupCode.Text = group.GroupCode;
                this.txtGroupName.Text = group.GroupName;
            }
            else if (this.tvContacts.SelectedNode.Level == 2)
            {
                pnlContact.Visible = true;
                pnlGroup.Visible = false;
                SMSContact contact = (SMSContact)this.tvContacts.SelectedNode.Tag;
                this.txtName.Text = contact.ContactName;
                this.txtMoble.Text = contact.ContactMobile;
                this.txtName.ReadOnly = true;
                this.txtMoble.ReadOnly = true;
                BindGroup();
                this.cmbGroup.SelectedValue = contact.SMSContactGroupID;
                this.cmbGroup.Enabled = false;
                this.btnSaveContact.Visible = false;
            }
        }

        private void tvContacts_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                this.tvContacts.SelectedNode = e.Node;
            }
        }

        /// <summary>
        /// 判断手机
        /// </summary>
        /// <param name="Mobil"></param>
        /// <returns></returns>
        public static bool IsValidateOfMobile(string Mobil)
        {
            //return Regex.IsMatch(Mobil, @"^(\d)+[-]?(\d){6,12}$");
            return Regex.IsMatch(Mobil, @"^(13|14|15|16|18|19)\d{9}$");


        }
    }
}
